<template>
  <div class="users">
    <el-card class="box-card">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/interface/index' }"
          >首页</el-breadcrumb-item
        >
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
      </el-breadcrumb>
      <div class="users_area">
        <div class="users_title">
          <!-- 搜索用户 -->
          <div class="ipt">
            <el-input
              placeholder="请输入用户名"
              v-model="params.query"
              class="input-with-select"
            >
              <template slot="prepend">搜索</template>
              <el-button
                slot="append"
                icon="el-icon-search"
                @click="user_search"
              ></el-button>
            </el-input>
          </div>
          <!-- 添加用户 -->
          <el-row>
            <el-button type="primary" @click="dialogFormVisible = true"
              >添加用户
            </el-button>
          </el-row>
        </div>
        <!-- 获取用户列表 -->
        <div class="users_msg">
          <el-table :data="tableData" height="400" border style="width: 100%">
            <el-table-column type="index" label="序号" width="50px">
            </el-table-column>
            <el-table-column prop="username" label="用户名" align="center">
            </el-table-column>
            <el-table-column prop="email" label="邮箱" align="center">
            </el-table-column>
            <el-table-column prop="mobile" label="电话" align="center">
            </el-table-column>
            <el-table-column prop="role_name" label="角色" align="center">
            </el-table-column>
            <el-table-column prop="mg_state" label="状态" align="center">
              <!-- 在组件中引入自己的结构 -->
              <template scope="swi">
                <!-- {{ swi.row }} -->
                <div>
                  <el-switch
                    v-model="swi.row.mg_state"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                    @change="modifyState(swi.row.id, swi.row.mg_state)"
                  >
                  </el-switch>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="" label="操作" align="center">
              <template scope="users">
                <div>
                  <!-- {{ users.row.id }} -->
                  <!-- 修改用户信息 -->
                  <!-- @click="editor(users.row.id)" -->
                  <!-- editorDialogFormVisible = true -->
                  <el-tooltip
                    class="item"
                    effect="dark"
                    content="修改信息"
                    placement="left-start"
                  >
                    <el-button
                      @click="editor(users.row)"
                      type="primary"
                      size="mini"
                      icon="el-icon-edit"
                    ></el-button>
                  </el-tooltip>
                  <!-- 分配用户角色信息 -->
                  <el-tooltip
                    class="item"
                    effect="dark"
                    content="分配用户角色信息"
                    placement="top-start"
                  >
                    <el-button
                      @click="role(users.row)"
                      type="warning"
                      size="mini"
                      icon="el-icon-setting"
                    ></el-button>
                  </el-tooltip>
                  <!-- 删除用户 -->
                  <el-tooltip
                    class="item"
                    effect="dark"
                    content="删除用户"
                    placement="top-start"
                  >
                    <el-button
                      type="danger"
                      size="mini"
                      icon="el-icon-delete"
                      @click="del(users.row.id)"
                    ></el-button>
                  </el-tooltip>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- 分页功能 -->
        <div class="block">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage4"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="5"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>
        </div>
      </div>
    </el-card>
    <!-- 新增用户弹窗 -->
    <el-dialog
      width="35%"
      title="新增用户"
      :visible.sync="dialogFormVisible"
      modal
      show-close
      center
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="ruleForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="ruleForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="ruleForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="ruleForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="user_d">确 定</el-button>
      </div>
    </el-dialog>
    <!--修改弹窗  -->
    <el-dialog
      width="35%"
      title="修改用户信息"
      :visible.sync="editorDialogFormVisible"
      modal
      show-close
      center
    >
      <el-form
        :model="amendRuleForm"
        :rules="editorRules"
        ref="amendRuleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="amendRuleForm.username"
            :disabled="true"
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="amendRuleForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="amendRuleForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editorDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="amendRuleForm_d">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 设置角色 -->
    <el-dialog
      width="35%"
      title="分配角色"
      :visible.sync="roleFormVisible"
      modal
      show-close
      center
    >
      <p style="margin: 14px 5px">当前用户：{{ username }}</p>
      <p style="margin: 10px 5px">当前角色：{{ role_name }}</p>
      <p>
        <el-form label-width="100px" class="demo-ruleForm">
          <el-form-item label="分配新角色">
            <el-select v-model="roleValue" placeholder="请选择">
              <el-option
                v-for="item in options"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </p>
      <div slot="footer" class="dialog-footer">
        <el-button @click="roleFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="roleRuleForm_d">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  name: "UserList",
  data() {
    return {
      roleValue: "", //角色
      user_val: "",
      value: "",
      user_value: true,
      currentPage4: 1,
      dialogFormVisible: false, //新增用户
      editorDialogFormVisible: false, //修改用户
      roleFormVisible: false, //设置用户角色
      total: 0,
      tableData: [],
      //设置用户角色
      options: [],
      roleVal: {
        id: 0,
        rid: 0,
      },
      username: "",
      role_name: "",
      usersId: 0,
      //添加用户表单验证规则
      ruleForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 9, message: "长度在 3 到 9 个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 12,
            message: "长度在 6 到 12 个字符",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { type: "email", message: "请输入正确的邮箱", trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            message: "请输入正确的手机号",
            trigger: "blur",
          },
        ],
      },
      //修改用户信息
      amendRuleForm: {
        username: "",
        id: "",
        email: "",
        mobile: "",
      },
      editorRules: {
        id: [
          { required: true, message: "id", trigger: "blur" },
          { type: "email", message: "请输入正确的邮箱", trigger: "blur" },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { type: "email", message: "请输入正确的邮箱", trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            message: "请输入正确的手机号",
            trigger: "blur",
          },
        ],
      },
      //请求对象
      params: {
        query: "",
        pagenum: 1,
        pagesize: 5,
      },
      form: {
        name: "",
        region: "",
        date1: "",
        date2: "",
        password: "",
        emai: "",
        // delivery: false,
        type: [],
        resource: "",
        desc: "",
        number: "",
      },
      formLabelWidth: "80px",
    };
  },
  methods: {
    //删除用户
    del(id) {
      console.log(id);
      this.MessageBox.confirm("此用户将永远删除, 是否继续?", "温馨提示:", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.axios.delete(`users/${id}`).then(
            (res) => {
              console.log(res);
              this.$message({
                message: "删除成功!",
                type: "success",
                center: "true",
              });
              this.usersList();
            },
            (err) => {
              console.log(err);
            }
          );
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //分配角色信息
    async role(row) {
      this.roleFormVisible = true;
      console.log(row);
      this.username = row.username; //用户表的用户名
      this.role_name = row.role_name; //用户表的角色名
      this.usersId = row.id; //用户表的用户id
      let res = await this.axios.get("roles");
      console.log(res);
      this.options = [];
      res.data.data.forEach((element) => {
        delete element.children;
        this.options.push(element);
      });
      console.log(this.options);
    },
    //确认分配角色信息
    async roleRuleForm_d() {
      console.log(this.roleValue, this.usersId);
      let res = await this.axios.put(`users/${this.usersId}/role`, {
        rid: this.roleValue,
      });
      console.log(res);
      if (res.data.meta.status == 200) {
        this.$message({
          type: "success",
          message: "分配角色成功！",
          center: "true",
        });
        this.roleFormVisible = false;
        this.usersList();
      } else {
        this.$message({
          type: "success",
          message: "分配角色失败！",
          center: "true",
        });
      }
    },
    //修改用户
    editor(row) {
      this.editorDialogFormVisible = true;
      this.amendRuleForm.username = row.username;
      this.amendRuleForm.id = row.id;
      console.log(row);
    },
    amendRuleForm_d() {
      this.axios.put(`users/${this.amendRuleForm.id}`, this.amendRuleForm).then(
        (res) => {
          if (res.data.meta.status == 200) {
            this.$message({
              message: `更新用户名:${res.data.data.username}成功!`,
              type: "success",
              center: "true",
            });
            this.editorDialogFormVisible = false;
            this.usersList();
            this.$refs["amendRuleForm"].resetFields();
          } else {
            this.$message({
              message: `更新用户名:${res.data.data.username}失败!`,
              type: "error",
              center: "true",
            });
          }
          console.log(res);
        },
        (err) => {
          console.log(err);
        }
      );
    },
    //添加用户信息
    user_d() {
      // console.log(this.userForm.name);
      this.$refs["ruleForm"].validate((val) => {
        if (val) {
          this.axios.post("users", this.ruleForm).then((res) => {
            console.log(res);
            if (res.data.meta.status == 201) {
              this.$message({
                message: "添加用户成功!",
                type: "success",
                center: "true",
              });
              this.dialogFormVisible = false;
              this.usersList();
              this.$refs["ruleForm"].resetFields();
            } else {
              this.$message({
                message: res.data.meta.msg,
                type: "warning",
                center: "true",
              });
            }
          });
        } else {
          console.log("error submit!!");
        }
      });
    },
    //根据用户名查询用户
    user_search() {
      if (this.params.query != "") {
        this.usersList();
        this.user_val = "";
      } else {
      }
    },
    //获取用户列表
    usersList() {
      this.axios
        .get("users", {
          params: this.params,
        })
        .then(
          (res) => {
            console.log(res, "获取用户列表");
            this.tableData = res.data.data.users;
            this.total = res.data.data.total;
          },
          (err) => {
            console.log(err);
          }
        );
    },
    //更新用户
    handleSizeChange() {},
    handleCurrentChange() {},
    //每页显示的条数
    handleSizeChange(e) {
      // console.log(e);
      this.params.pagesize = e;
      this.usersList();
    },
    //当前页
    handleCurrentChange(e) {
      console.log(e);
      this.params.pagenum = e;
      this.usersList();
    },
    //修改用户状态
    modifyState(id, val) {
      console.log(id, val);
      this.axios.put(`users/${id}/state/${val}`).then((res) => {
        if (res.data.data.mg_state == 0) {
          this.$message({
            message: "用户已禁用!",
            type: "error",
            center: "true",
          });
        } else {
          this.$message({
            message: "用户已启用!",
            type: "success",
            center: "true",
          });
        }
      });
    },
  },
  mounted() {
    this.usersList();
  },
};
</script>

<style lang='less' scope>
.users {
  width: 100%;
  .el-card__body {
    height: 77vh;
    .users_area {
      width: 100%;
      height: 77vh;
      margin: 20px auto;
      margin-bottom: 0px;
      .users_title {
        width: 100%;
        height: 80px;
        display: flex;
        align-items: center;
        .el-form-item__label:before {
          content: "*";
          color: #f56c6c;
          margin-right: 4px;
        }
        .el-row {
          margin: 30px;
        }
        .ipt {
          .el-input__inner {
            width: 300px;
          }
        }
        .el-select .el-input {
          width: 100px;
        }
        .input-with-select .el-input-group__prepend {
          background-color: #fff;
        }
      }
      .users_msg {
        width: 100%;
        height: 400px;
        .cell {
          text-align: center;
        }
        .el-table__body {
          height: 100% !important;
        }
      }
      .block {
        height: 100px;
        display: flex;
        justify-content: center;
        align-items: center;
      }
    }
  }
}
</style>